package com.gombe.credit.app.sdk.analyse.util

import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustAttribution
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.LogLevel
import com.gombe.credit.app.configs.GombeCreditConfigs
import com.gombe.credit.app.sdk.analyse.GombeCreditAnalyseBuilder
import com.gombe.credit.app.sdk.analyse.bean.GombeCreditAdjustBean
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.google.firebase.FirebaseApp

object GombeCreditAdjustUtil {

    /** adjust env */
    private const val AJ_ENVIRONMENT = AdjustConfig.ENVIRONMENT_PRODUCTION

    /** adjust token */
    private const val AJ_TOKEN = GombeCreditConfigs.GOMBECREDIT_ADJ_TOKEN // TODO: 填写对应的值

    /** 归因信息 */
    private var _adjsutAttribution: GombeCreditAdjustBean? = null

    /**
     * 初始化Adjust模块
     * 按配置需要来初始化
     *
     * @param context Application
     */
    fun init(context: Application) {
        // 按需要判断，3个key值不能为空
        if (AJ_TOKEN.isBlank()) throw Exception("Error: Adjust Token must no be null!")

        if (GombeCreditAnalyseBuilder.zone.isBlank()) return
        // Initialize Firebase App
        FirebaseApp.initializeApp(context)

        val config = AdjustConfig(context, AJ_TOKEN, AJ_ENVIRONMENT)
        config.setLogLevel(LogLevel.INFO)
        config.setOnAttributionChangedListener { saveAttribution(it) }
        Adjust.initSdk(config)

        registerAdjustActivityLifecycle(context)

        Adjust.getAttribution { var0->
            saveAttribution(var0)
        }
    }

    private fun saveAttribution(attribution: AdjustAttribution?) {
        attribution?.let { result ->
            _adjsutAttribution = GombeCreditAdjustBean()
            _adjsutAttribution?.let { params ->
                Adjust.getAdid {
                    params.adid = it.orEmpty()
                }
                params.network = result.network.orEmpty()
                params.adgroup = result.adgroup.orEmpty()
                params.creative = result.creative.orEmpty()
                params.costType = result.costType.orEmpty()
                params.campaign = result.campaign.orEmpty()
                params.clickLabel = result.clickLabel.orEmpty()
                params.trackerName = result.trackerName.orEmpty()
                params.trackerToken = result.trackerToken.orEmpty()
                params.costCurrency = result.costCurrency.orEmpty()
                params.fbInstallReferrer = result.fbInstallReferrer.orEmpty()
                result.costAmount?.let { costAmount ->
                    params.costAmount = costAmount.toString()
                }

                //上报
                GombeCreditLogger.i("=====adjust attribution finish")
                saveInstallInfo()
            }
        }
    }

    private fun saveInstallInfo() {
        try {
            _adjsutAttribution?.let { data ->
                val path = GombeCreditAnalyseBuilder.pathAdjustInstall
                val url = UrlHelper.combineUrl()
                val body = data.encrypt(path)
                AnalyseRequestUtil.doPostAction(url, body)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun registerAdjustActivityLifecycle(context: Application) {
        context.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) {
            }

            override fun onActivityStarted(p0: Activity) {
            }

            override fun onActivityResumed(p0: Activity) {
                Adjust.onResume()
            }

            override fun onActivityPaused(p0: Activity) {
                Adjust.onPause()
            }

            override fun onActivityStopped(p0: Activity) {
            }

            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
            }

            override fun onActivityDestroyed(p0: Activity) {
            }
        })
    }
}